package com.yupi.usercenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.common.BaseResponse;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.common.ResultUtils;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.model.domain.Team;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.domain.UserTeam;
import com.yupi.usercenter.model.dto.TeamAddRequest;
import com.yupi.usercenter.model.dto.TeamJoinRequest;
import com.yupi.usercenter.model.dto.TeamQuery;
import com.yupi.usercenter.model.dto.TeamUpdateRequest;
import com.yupi.usercenter.model.vo.TeamUserVO;
import com.yupi.usercenter.service.TeamService;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.bean.validators.plugins.schema.IsNullAnnotationPlugin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 */

@RestController
@RequestMapping
@CrossOrigin(origins = "*")
@Slf4j
/*
作用：用于映射Web请求到具体的处理方法
功能：
可以标注在类或方法上
定义请求的URL路径、HTTP方法、请求参数等条件
参数：需要指定映射路径（如 @RequestMapping("/team")）
 */
public class TeamController {
    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Autowired
    private UserTeamService userTeamService;


    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamadd, HttpServletRequest httpServletRequest)  {
        if (teamadd == null)  throw   new BusinessException(ErrorCode.PARAMS_ERROR);
        User serviceLoginUser = userService.getLoginUser(httpServletRequest);
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team,teamadd);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        long l = teamService.addTeam(team, serviceLoginUser);

        if (l <0) throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        return ResultUtils.success(team.getId());
    }
//    @DeleteMapping("/delete")
//    public BaseResponse<Boolean> deleteTeam(@RequestBody Long id){
//        if (id == null)  throw   new BusinessException(ErrorCode.PARAMS_ERROR);
//        boolean remove = teamService.removeById(id);
//        if (!remove) {
//            log.error("删除失败!");
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
//        }
//        return ResultUtils.success(remove);
//    }
    /**
     * 更新队伍
     * @param team
     * @return
     */
    @PostMapping("/updateTeam")
    public BaseResponse<Boolean > updaeTeam(@RequestBody TeamUpdateRequest  team,
                                            HttpServletRequest httpServletRequest){
        if (team == null) throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean b = teamService.updateTeam(team,loginUser);
        if (!b){
            log.error("更新失败!");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return ResultUtils.success(b);
    }

    @GetMapping("/getbyid")
    public BaseResponse<Team> getTeamById(@RequestParam Long id){
        if(id == null) throw  new BusinessException(ErrorCode.PARAMS_ERROR);

        Team byId = teamService.getById(id);
        if (byId == null){
            log.error("查询失败!");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"查询失败");
        }
        return ResultUtils.success(byId);
    }

    // 合并原来的两个list接口为一个，通过参数区分
    @GetMapping("/list")
    public  BaseResponse<List<TeamUserVO>> ListTeams(TeamQuery teamQuery, HttpServletRequest httpServletRequest){
        if (teamQuery == null) throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team,teamQuery );
        } catch (IllegalAccessException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        } catch (InvocationTargetException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean admin = userService.isAdmin(httpServletRequest);
        
        // 如果查询条件包含userId，则查询该用户创建的队伍
        if (teamQuery.getUserId() != null && teamQuery.getUserId() > 0) {
            admin = true;
            teamQuery.setUserId(loginUser.getId());
        } 
        // 如果查询条件包含特殊标记，查询该用户加入的队伍
        else if (teamQuery.getIdList() != null && teamQuery.getIdList().isEmpty()) {
            QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            List<UserTeam> teamList = userTeamService.list(userTeamQueryWrapper);
            ArrayList<Long> longs = teamList.stream().map(UserTeam::getTeamId).distinct().collect(Collectors.toCollection(ArrayList::new));
            teamQuery.setIdList(longs);
            admin = true;
        }
        
        List<TeamUserVO> list = teamService.listTeams(teamQuery, admin);
        return ResultUtils.success(list);
    }
    
    @GetMapping("/list/page")
    public  BaseResponse<Page<Team>>  ListTeamsPage(TeamQuery teamQuery){
        if (teamQuery == null) throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        Team team = new Team();
        long current = teamQuery.getPageNum()  ;
        long size= teamQuery.getPageSize() ;
        Page<Team> teamPage = new Page<>(current, size);
        try {
            BeanUtils.copyProperties(team,teamQuery);
        } catch (IllegalAccessException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        } catch (InvocationTargetException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>(team);

        Page<Team> page = teamService.page(teamPage, teamQueryWrapper);

        return ResultUtils.success(page);
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest httpServletRequest){
        if (teamJoinRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean joinTeam=   teamService.joinTeam(teamJoinRequest,httpServletRequest, loginUser);
        return ResultUtils.success(joinTeam);

    }
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamJoinRequest teamJoinRequest,HttpServletRequest httpServletRequest){
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);

        }
        User loginUser = userService.getLoginUser(httpServletRequest);
      Boolean quitTeam=  teamService.quitTeam(teamJoinRequest,httpServletRequest,loginUser);
      return ResultUtils.success(quitTeam);

    }
/**
 * 删除队伍
 * @param id
 * @return
 */
    @DeleteMapping("/deleteTeam")
    public BaseResponse<Boolean> deleteTeam(@RequestBody Long id,HttpServletRequest httpServletRequest){
        if (id == null)  throw   new BusinessException(ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean remove = teamService.deleteTeam(id,loginUser);
        if (!remove) {
            log.error("删除失败!");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return ResultUtils.success(remove);
    }
    
    // 删除重复的list接口，将其功能合并到上面的ListTeams方法中
    
    // 删除重复的listJoinTeam接口，将其功能合并到上面的ListTeams方法中

    @GetMapping("/match")
    public BaseResponse<List<User>> matcherUser(long num,HttpServletRequest httpServletRequest){

        if (num <= 0|| num > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(httpServletRequest);

        List<User> users = userService.matcherUser(num, loginUser);
        return ResultUtils.success(users);
    }


}